package system

import (
	"context"
	"errors"
	"github.com/dgrijalva/jwt-go"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
	"server/global"
	"server/model/system"
	"time"
)

type JwtService struct {
	SigningKey       []byte
	CachePrefix      string
	CacheBlackPrefix string
}

type CustomClaims struct {
	BaseClaims
	BufferTime int64
	jwt.StandardClaims
}

type BaseClaims struct {
	UUID  uuid.UUID
	ID    uint
	Email string
	Name  string
}

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

//方便调用
var SysJwtApp = &JwtService{
	[]byte(global.GvaConfig.JWT.SigningKey),
	"jwt:",
	"jwt_black_list",
}

func (j *JwtService) CreateClaims(baseClaims BaseClaims) CustomClaims {
	claims := CustomClaims{
		BaseClaims: baseClaims,
		BufferTime: global.GvaConfig.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 1000,                             // 签名生效时间
			ExpiresAt: time.Now().Unix() + global.GvaConfig.JWT.ExpiresTime, // 过期时间 7天  配置文件
			Issuer:    global.GvaConfig.JWT.Issuer,                          // 签名的发行者
		},
	}
	return claims
}

// 创建一个token
func (j *JwtService) CreateToken(claims CustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func (j *JwtService) CreateTokenByOldToken(oldToken string, claims CustomClaims) (string, error) {
	v, err, _ := global.GvaConcurrencyControl.Do(j.CachePrefix+oldToken, func() (interface{}, error) {
		return j.CreateToken(claims)
	})
	return v.(string), err
}

// 解析 token
func (j *JwtService) ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid
	} else {
		return nil, TokenInvalid
	}
}

//从redis取jwt
func (j *JwtService) GetRedisJWT(uuid string) (err error, redisJWT string) {
	redisJWT, err = global.GvaRedis.Get(context.Background(), j.CachePrefix+uuid).Result()
	return err, redisJWT
}

//jwt存入redis并设置过期时间
func (j *JwtService) SetRedisJWT(jwt string, uuid string) (err error) {
	// 此处过期时间等于jwt过期时间
	timer := time.Duration(global.GvaConfig.JWT.ExpiresTime) * time.Second
	err = global.GvaRedis.Set(context.Background(), j.CachePrefix+uuid, jwt, timer).Err()
	return err
}

//拉黑jwt
func (j *JwtService) JsonInBlacklist(jwtList system.SysJwtBlacklist) (err error) {
	err = global.GvaDb.Create(&jwtList).Error
	if err != nil {
		return
	}
	err = global.GvaRedis.SAdd(context.Background(), j.CacheBlackPrefix, jwtList.Jwt).Err()
	//global.BlackCache.SetDefault(jwtList.Jwt, struct{}{})
	return
}

//判断JWT是否在黑名单内部
func (j *JwtService) IsBlacklist(jwt string) bool {
	rs, err := global.GvaRedis.SIsMember(context.Background(), j.CacheBlackPrefix, jwt).Result()
	if err == nil && rs {
		return true
	}
	return false
	//_, ok := global.BlackCache.Get(jwt)
	//return ok
	//err := global.GVA_DB.Where("jwt = ?", jwt).First(&system.SysJwtBlacklist{}).Error
	//isNotFound := errors.Is(err, gorm.ErrRecordNotFound)
	//return !isNotFound
}
func InitJwtBlackList() {
	var data []string
	err := global.GvaDb.Model(&system.SysJwtBlacklist{}).Select("jwt").Find(&data).Error
	if err != nil {
		global.GvaLog.Error("加载数据库jwt黑名单失败!", zap.Error(err))
		return
	}
	for i := 0; i < len(data); i++ {
		err = global.GvaRedis.SAdd(context.Background(), SysJwtApp.CacheBlackPrefix, data[i]).Err()
		//global.BlackCache.SetDefault(data[i], struct{}{})
	} // jwt黑名单 加入 BlackCache 中
}
